package com.jesper.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jesper.model.Config;
import com.jesper.service.ConfigService;
import com.jesper.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@Slf4j
public class ConfigController {

    @Autowired
    ConfigService configService;

    @RequestMapping("user/config_{pageCurrent}_{pageSize}_{pageCount}")
    public String config(Config config, @PathVariable Integer pageCurrent,
                         @PathVariable Integer pageSize,
                         @PathVariable Integer pageCount, Model model) {
        if (pageSize == 0) pageSize = 50;
        if (pageCurrent == 0) pageCurrent = 1;

        Page<Config> configPage = configService.query(pageCurrent, pageSize, config);
        int rows = new Long(configPage.getTotal()).intValue();
        if (pageCount == 0) pageCount = rows % pageSize == 0 ? (rows / pageSize) : (rows / pageSize) + 1;
        config.setStart((pageCurrent - 1) * pageSize);
        config.setEnd(pageSize);
        List<Config> configList = configPage.getRecords();
        String pageHTML = PageUtil.getPageContent("config_{pageCurrent}_{pageSize}_{pageCount}", pageCurrent, pageSize, pageCount);
        model.addAttribute("config", configList);
        model.addAttribute("pageHTML", pageHTML);
        return "user/config";
    }

    @GetMapping("/user/configEdit")
    public String configEdit(Integer id, Model model) {
        if (id == null) {
            Config config = new Config();
            model.addAttribute("con", config);
        } else {
            Config config = configService.getById(id);
            model.addAttribute("con", config);
        }
        return "user/configEdit";

    }

    @PostMapping("/user/configEdit")
    public String postConfigEdit(Config config, Model model) {
        if (config.getId() == null) {
            configService.save(config);
        } else {
            configService.updateById(config);
        }
        return "redirect:/user/config_0_0_0";

    }

    @GetMapping("/user/configDelete/{id}")
    public String deleteConfig(@PathVariable Integer id) {
        configService.removeById(id);
        return "redirect:/user/config_0_0_0";
    }
}
